import {Component, ViewEncapsulation} from '@angular/core';
import {UserService} from '../../../../services/app.user';
import {BaThemeSpinner}  from '../../../../theme/services';
import {LocalDataSource} from 'ng2-smart-table';
declare let toastr:any;
declare let $:any;
declare var jQuery:any;
@Component({
    selector: 'Version',
    encapsulation: ViewEncapsulation.None,
    templateUrl: './version.html',
    styleUrls: ['./version.scss'],
})

export class Version {
    query:string = '';

    settings = {
        add: {
            addButtonContent: '<i class="ion-ios-plus-outline"></i>',
            createButtonContent: '<i class="ion-checkmark"></i>',
            cancelButtonContent: '<i class="ion-close"></i>',
        },
        edit: {
            editButtonContent: '<i class="ion-edit"></i>',
            saveButtonContent: '<i class="ion-checkmark"></i>',
            cancelButtonContent: '<i class="ion-close"></i>',
        },
        delete: {
            deleteButtonContent: '<i class="ion-unlocked"></i>',
            confirmDelete: true
        },
        columns: {
            name: {
                title: 'Name',
                type: 'string'
            },
            description: {
                title: 'Description',
                type: 'string'
            },
            male: {
                title: 'Total No. of males',
                type: 'string'
            },
            female: {
                title: 'Total No. of females',
                type: 'string'
            },
            Total: {
                title: 'Total count',
                type: 'string'
            }
        }
    };

    source:LocalDataSource = new LocalDataSource();

    public start:any;
    public end:any;
    public check:any;

    constructor(private userService:UserService, private spinner:BaThemeSpinner) {
        this.start = 0;
        this.check = 0;

        // Function for start timeline count
        this.startCount();
    }

    // Function for get version info
    ngAfterViewInit() {
        let data = {};
        this.spinner.showProgress();
        this.userService.getVersionings(data).subscribe(
            data => {
                this.versionData(data);
            });
    }

    // Set versioning data to smart table
    public versionData(data) {
        this.source.load(data);
        this.getAllVersioning();
        this.spinner.hideProgress();
    }

    // API call for get all version info
    public getAllVersioning() {
        this.userService.getAllVersion({}).subscribe(
            data => {
                this.allVersionStatus(data);
            });
    }

    // Function for set lock unlock icon after API success
    public allVersionStatus(data) {

        for (let i = data.length - 1; i >= 0; i--) {

            if (data[i].name === 'Version_8' && data[i].isLocked === true) {
                $('.ion-unlocked').each(function (i) {
                    if (i === 7) {
                        $(this).removeClass();
                        $(this).addClass('ion-locked');
                    }
                });

            } else if (data[i].name === 'Version_7' && data[i].isLocked === true) {
                $('.ion-unlocked').each(function (i) {
                    if (i === 6) {
                        $(this).removeClass();
                        $(this).addClass('ion-locked');
                    }
                });
            } else if (data[i].name === 'Version_6' && data[i].isLocked === true) {
                $('.ion-unlocked').each(function (i) {
                    if (i === 5) {
                        $(this).removeClass();
                        $(this).addClass('ion-locked');
                    }
                });
            } else if (data[i].name === 'Version_5' && data[i].isLocked === true) {
                $('.ion-unlocked').each(function (i) {
                    if (i === 4) {
                        $(this).removeClass();
                        $(this).addClass('ion-locked');
                    }
                });
            } else if (data[i].name === 'Version_4' && data[i].isLocked === true) {
                $('.ion-unlocked').each(function (i) {
                    if (i === 3) {
                        $(this).removeClass();
                        $(this).addClass('ion-locked');
                    }
                });
            } else if (data[i].name === 'Version_3' && data[i].isLocked === true) {
                $('.ion-unlocked').each(function (i) {
                    if (i === 2) {
                        $(this).removeClass();
                        $(this).addClass('ion-locked');
                    }
                });
            } else if (data[i].name === 'Version_2' && data[i].isLocked === true) {
                $('.ion-unlocked').each(function (i) {
                    if (i === 1) {
                        $(this).removeClass();
                        $(this).addClass('ion-locked');
                    }
                });
            } else if (data[i].name === 'Version_1' && data[i].isLocked === true) {
                $('.ion-unlocked').each(function (i) {
                    if (i === 0) {
                        $(this).removeClass();
                        $(this).addClass('ion-locked');
                    }
                });
            }
        }
    }


    // Function for version lock and unlock
    onDeleteConfirm(event):void {

        let x = jQuery(':contains("' + event.data.name + '")').last().parents('.ng2-smart-row').find('.ng2-smart-action-delete-delete i').attr('class');

        if (x === 'ion-unlocked') {
            this.spinner.showProgress();
            let input = {
                'versionName': event.data.name
            };
            // API call for lock version
            this.userService.versionLockUnlock(input).subscribe(
                data => this.getVersionLockStatus(data),
                error => this.getVersionLockError(error)
            );
            jQuery(':contains("' + event.data.name + '")').last().parents('.ng2-smart-row').find('.ng2-smart-action-delete-delete i').removeClass('ion-unlocked').addClass('ion-locked');
        } else {
            this.spinner.showProgress();
            let input = {
                'versionName': event.data.name
            };
            // API call for unlock version
            this.userService.versionLockUnlock(input).subscribe(
                data => this.getVersionUnlockStatus(data),
                error => this.getVersionLockError(error)
            );
            jQuery(':contains("' + event.data.name + '")').last().parents('.ng2-smart-row').find('.ng2-smart-action-delete-delete i').removeClass('ion-locked').addClass('ion-unlocked');
        }
    }

    // Function for version lock successfully
    public getVersionLockStatus(data) {
        toastr.success('Version locked successfully');
        this.spinner.hideProgress();
    }

    // Function for version unlock successfully
    public getVersionUnlockStatus(data) {
        toastr.success('Version unlocked successfully');
        this.spinner.hideProgress();
    }

    // Function for version lock error
    public getVersionLockError(err) {
        toastr.error('Error');
    }

    // To call every 1 sec for count how much time we spent on this page
    public  timedCount() {
        this.start = this.start + 1;
        this.end = setTimeout(() => {
            this.timedCount()
        }, 1);
    }

    // To function for start timstamp count
    public startCount() {
        if (!this.check) {
            this.check = 1;
            this.timedCount();
        }
    }

    // To function for stop timstamp count
    public stopCount() {
        clearTimeout(this.end);
        this.check = 0;
    }

    // To call this function when leave from this controller
    ngOnDestroy() {
        // To stop count function call
        this.stopCount();

      // API call for tract navigation sequence
      let seq = {
        sequence: {
          "pageName": 'admin/versioning',
          "timeSpent": this.start
        }

      };
      this.userService.setUrlSeq(seq).subscribe();

    }

    // Function call after view for log API
    ngAfterViewChecked() {
        let self = this;
        $('.row.versioningLog').unbind().mousedown(function (event) {
            self.checkAllLogs(event);
        });
    }

    // Function for check all logs
    public checkAllLogs(event) {
        let self = this;
        let buttons;
        if (event.button === 0) {
            buttons = 'left click';
        } else if (event.button === 1) {
            buttons = 'roller click';
        } else {
            buttons = 'right click';
        }
        let domTarget = event.target;
        let domTargetString = domTarget.toString();
        let stringDemo = domTargetString.substr(12, 25);
        let index = stringDemo.indexOf('E');
        let dom = stringDemo.substr(0, index);
        let text = $(event.target).unbind().text();


        let input = {
            'target': dom + ' ' + text,
            'value': text,
            'action': buttons
        };

        if (text.indexOf('×') >= 0) {
            let input = {
                'target': 'Closed modal',
                'value': '',
                'action': buttons
            };

            self.userService.setUserLogs(input).subscribe();

        } else if (event.target.className.indexOf('ng2-smart-page-link page-link') >= 0) {
            let input = {
                'target': 'Pagination',
                'value': '',
                'action': buttons
            };

            self.userService.setUserLogs(input).subscribe();

        } else {
            self.setUserLogs(input);
        }
    }

    // Function for call API for log
    public setUserLogs(input) {

        this.userService.setUserLogs(input).subscribe();
    }
}
